package com.Iconcat.system.controller;

import com.Iconcat.system.entity.QRCodeEntity;
import com.Iconcat.system.response.Result;
import com.Iconcat.system.service.QRCodeService;
import com.Iconcat.system.vo.QRCodeRequest;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;

import com.google.zxing.common.BitMatrix;
import io.swagger.annotations.Api;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Map;

@RestController
@RequestMapping("/payment")
@CrossOrigin
@Api(value = "支付", tags = "支付接口")
public class PaymentController {
    @Resource
    private QRCodeService qrCodeService;

    @PostMapping("/generateQRCode")
    public Result generateQRCode(@RequestBody QRCodeRequest request) {
        try {
            // 生成二维码的逻辑
            BufferedImage qrCodeImage = generateQRCodeImage(request.getData());

            // 数据库操作
            updateOrInsertQRCode(request.getData());

            // 返回 Result
            return Result.ok().data("qrcode", convertBufferedImageToByteArray(qrCodeImage));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error().message("生成二维码失败");
        }
    }

    @GetMapping("/getQRCode")
    public Result getQRCode() {
        try {
            // 查询数据库获取存储的二维码
            QRCodeEntity storedQRCode = qrCodeService.lambdaQuery().last("LIMIT 1").one();

            if (storedQRCode != null) {
                // 生成 BufferedImage
                BufferedImage qrCodeImage = generateQRCodeImage(storedQRCode.getQrCodeData());

                // 将 BufferedImage 转换为字节数组
                byte[] qrCodeByteArray = convertBufferedImageToByteArray(qrCodeImage);

                // 设置HTTP响应头
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.IMAGE_PNG);
                headers.setContentLength(qrCodeByteArray.length);

                // 返回响应实体
                return Result.ok().data("qrcode", qrCodeByteArray).data("qrData", storedQRCode.getQrCodeData());
            } else {
                return Result.error().message("未找到存储的二维码");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error().message("获取二维码失败");
        }
    }

    private BufferedImage generateQRCodeImage(String data) {
        try {
            int width = 300;
            int height = 300;

            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            BitMatrix bitMatrix = multiFormatWriter.encode(data, BarcodeFormat.QR_CODE, width, height);

            // 将 BitMatrix 转换为 BufferedImage
            BufferedImage qrCodeImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    qrCodeImage.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
                }
            }

            return qrCodeImage;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private void updateOrInsertQRCode(String data) {
        // 查询是否已存在二维码数据
        QRCodeEntity existingQRCode = qrCodeService.getOne(Wrappers.emptyWrapper());

        if (existingQRCode != null) {
            // 存在则更新数据
            existingQRCode.setQrCodeData(data);
            existingQRCode.setCreatedAt(LocalDateTime.now());
            qrCodeService.updateById(existingQRCode);
        } else {
            // 不存在则插入新数据
            QRCodeEntity newQRCodeEntity = new QRCodeEntity();
            newQRCodeEntity.setQrCodeData(data);
            newQRCodeEntity.setCreatedAt(LocalDateTime.now());
            qrCodeService.save(newQRCodeEntity);
        }
    }

    private byte[] convertBufferedImageToByteArray(BufferedImage image) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "png", baos);
            return baos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return new byte[0];
        }
    }

}






